package com.crr.service.impl;

import com.crr.api.bean.StockDto;
import com.crr.api.feign.SpuRemoteClient;
import com.crr.bean.Order;
import com.crr.bean.OrderAddr;
import com.crr.bean.ResultBean;
import com.crr.crud.MyBaseServiceImpl;
import com.crr.ex.BusinessException;
import com.crr.mapper.OrderAddrMapper;
import com.crr.mapper.OrderItemMapper;
import com.crr.mapper.OrderMapper;
import com.crr.service.OrderService;
import com.crr.utils.Assert;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class OrderServiceImpl extends MyBaseServiceImpl<Order, OrderMapper> implements OrderService {
    @Autowired
    OrderAddrMapper orderAddrMapper;
    @Autowired
    OrderItemMapper orderItemMapper;
    @Autowired
    SpuRemoteClient spuRemoteClient;

    @GlobalTransactional
    @Override
    public int saveEntity(Order entity) {
        OrderAddr orderAddr = entity.getOrderAddr();
        int i = orderAddrMapper.insert(orderAddr);
        Assert.isNotSuccess(i, "地址保存成功！");
        //设置收货地址id
        entity.setOrder_addr_id(orderAddr.getOrder_addr_id());
        i = baseMapper.insert(entity);
        Assert.isNotSuccess(i, "订单保存成功！");
        if (null != entity.getOrderItemList() && entity.getOrderItemList().size() > 0) {
            int res = orderItemMapper.bachSave(entity.getOrder_id(), entity.getOrderItemList());
            Assert.isNotSuccess(res, "订单明细保存成功！");

            //更新库存
            //遍历订单明细有几条 加入更新库存的数据有几条
            List<StockDto> beanList = new ArrayList<>();
            entity.getOrderItemList().forEach(el -> {
                beanList.add(new StockDto(el.getSpu_id(), el.getSku_id(), el.getCount(), el.getOrder_id()));

            });

            //更新库存
            ResultBean resultBean = spuRemoteClient.updateStock(beanList);
            if (resultBean.getCode() != 200) {
                throw new BusinessException("更新库存失败" + resultBean.getMessage());
            }
        }

        return 1;
    }

}
